import instanceRegistryManager from './instance.registry'

export interface IappPort {
    masterPort: number,
    childPort: number,
    websocketPort: number,
}

// 端口注册管理器 - 统一使用instance.registry.ts管理端口
class PortRegistryManager {
    // 单例模式实例管理器
    private static instance: PortRegistryManager;
    private instanceName: string | null = null;
    private instanceRegistry: instanceRegistryManager;
    
    public static get getInstance() {
        if (!this.instance) {
            this.instance = new PortRegistryManager();
        }
        return this.instance;
    }
    
    constructor() {
        this.instanceRegistry = instanceRegistryManager.getInstance;
    }
    
    // 获取当前实例名称
    private async getCurrentInstanceName(): Promise<string> {
        if (!this.instanceName) {
            // 查找可复用的非活跃实例
            this.instanceName = await this.instanceRegistry.findBeforeInstanceId();
            
            if (this.instanceName) {
                // 如果找到非活跃实例，将其激活
                await this.instanceRegistry.activateInstance(this.instanceName);
            } else {
                // 如果没有可复用的实例，抛出错误而不是创建新实例
                // 实例应该由主进程的registerApplication方法统一创建
                throw new Error('没有可用的实例，请确保主进程已正确注册实例');
            }
        }
        return this.instanceName;
    }
    
    // 随机分配应用端口
    public async randomAppPort(): Promise<IappPort> {
        try {
            const instanceName = await this.getCurrentInstanceName();
            console.log(`为实例 ${instanceName} 分配端口...`);
            
            // 使用统一的端口分配方法
            const portConfig = await this.instanceRegistry.allocatePortsForInstance(instanceName);
            
            const result: IappPort = {
                masterPort: portConfig.masterPort,
                childPort: portConfig.childPort,
                websocketPort: portConfig.websocketPort
            };
            
            console.log(`实例 ${instanceName} 端口分配完成:`, result);
            return result;
            
        } catch (error) {
            console.error('端口分配失败:', error);
            throw error;
        }
    }
    
    // 释放端口
    public async releasePort(): Promise<void> {
        try {
            if (this.instanceName) {
                console.log(`释放实例 ${this.instanceName} 的端口...`);
                await this.instanceRegistry.releaseInstancePorts(this.instanceName);
                console.log(`实例 ${this.instanceName} 端口释放完成`);
            } else {
                // 如果没有实例名称，尝试根据PID释放
                await this.instanceRegistry.releasePortsByPid(process.pid);
                console.log(`根据PID ${process.pid} 释放端口完成`);
            }
        } catch (error) {
            console.error('端口释放失败:', error);
            throw error;
        }
    }
    
    // 获取当前实例的端口配置
    public async getCurrentPorts(): Promise<IappPort | null> {
        try {
            const instanceName = await this.getCurrentInstanceName();
            const registry = await this.instanceRegistry.readRegistryJson();
            const instance = registry.database[instanceName];
            
            if (instance && instance.ports) {
                return {
                    masterPort: instance.ports.masterPort,
                    childPort: instance.ports.childPort,
                    websocketPort: instance.ports.websocketPort
                };
            }
            
            return null;
        } catch (error) {
            console.error('获取当前端口配置失败:', error);
            return null;
        }
    }
    
    // 检查端口是否可用
    public async isPortAvailable(port: number): Promise<boolean> {
        try {
            const registry = await this.instanceRegistry.readRegistryJson();
            
            for (const instanceName in registry.database) {
                const instance = registry.database[instanceName];
                if (instance.ports && instance.isActive) {
                    if (instance.ports.masterPort === port || 
                        instance.ports.childPort === port || 
                        instance.ports.websocketPort === port) {
                        return false;
                    }
                }
            }
            
            return true;
        } catch (error) {
            console.error('检查端口可用性失败:', error);
            return false;
        }
    }
    
    // 清理非活跃实例的端口
    public async cleanupInactivePorts(): Promise<void> {
        try {
            await this.instanceRegistry.checkAndUpdateInstanceStatus();
            console.log('非活跃实例端口清理完成');
        } catch (error) {
            console.error('清理非活跃实例端口失败:', error);
        }
    }
}

export default PortRegistryManager;